var express = require('express');
var router = express.Router();
const fs = require('fs')
const path = require('path')
const mkdirp = require('mkdirp')

function suffix() {
    const date = new Date();
    const y = date.getFullYear()
    let M = date.getMonth() + 1
    M = M < 10 ? ('0' + M) : M
    let d = date.getDate()
    d = d < 10 ? ('0' + d) : d;
    let h = date.getHours()
    h = h < 10 ? ('0' + h) : h;
    let m = date.getMinutes()
    m = m < 10 ? ('0' + m) : m;
    let s = date.getSeconds()
    s = s < 10 ? ('0' + s) : s;
    return `${y}${M}${d}_${h}_${m}_${s}`
}

router.get('/files', function (req, res, next) {
    const copyDir = path.join(__dirname, '../../copy')
    const deletedDir = path.join(__dirname, '../../deleted')
    if (!fs.existsSync(copyDir)) mkdirp.sync(copyDir)
    if (!fs.existsSync(deletedDir)) mkdirp.sync(deletedDir)
    const dir = path.join(__dirname, '../../0110000100000666')
    // console.log('dir', dir)
    const files = fs.readdirSync(dir).filter(f => f !== 'DS2SOFS0000.sl2').sort().reverse()
    res.json(files)
})

router.post('/save-copy', function (req, res, next) {
    const dir = path.join(__dirname, '../../0110000100000666')
    const src = dir + '/DS2SOFS0000.sl2'
    const dest = dir + '/DS2SOFS0000.sl2_' + suffix()
    fs.copyFileSync(src, dest)
    res.send('ok')
})

router.post('/delete-batch', function (req, res, next) {
    const files = req.body
    // console.log(files)
    files.forEach(f => {
        const mvFrom = path.join(__dirname, '../../0110000100000666',f)
        const mvTo = path.join(__dirname, '../../deleted',f)
        fs.renameSync(mvFrom, mvTo)
    })
    res.send('ok')
})

router.post('/restore', function (req, res, neededEvent) {
    const f = req.query.file
    const dir = path.join(__dirname, '../../0110000100000666')
    const dest = dir + '/DS2SOFS0000.sl2'
    const src = dir + '/' + f

    const copyTo = path.join(__dirname, '../../copy', 'DS2SOFS0000.sl2_' + suffix())
    fs.copyFileSync(dest, copyTo) // 先把“即将被覆盖的文件”留存一份

    fs.copyFileSync(src, dest)
    res.send('ok')
})

module.exports = router;
